package crmdna.inventory;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import crmdna.common.UnitUtils;
import crmdna.common.UnitUtils.PhysicalQuantity;
import crmdna.common.UnitUtils.ReportingUnit;

public class InventoryItemProp implements Comparable<InventoryItemProp> {
	long inventoryItemId;

	long groupId;
	long inventoryItemTypeId;

	String displayName;
	PhysicalQuantity physicalQuantity;
	ReportingUnit reportingUnit;

	double quantityInDefaultUnit;

	// dependents
	String inventoryItemType;
	double quantityInReportingUnit;

	public static void populateDependents(String client,
			Iterable<InventoryItemProp> props) {

		Set<Long> inventoryItemTypeIds = new HashSet<>();
		for (InventoryItemProp prop : props) {
			inventoryItemTypeIds.add(prop.inventoryItemTypeId);
		}

		Map<Long, InventoryItemEntity> map = InventoryItemType.get(client,
				inventoryItemTypeIds);

		for (InventoryItemProp prop : props) {
			if (map.containsKey(prop.inventoryItemId)) {
				prop.inventoryItemType = map.get(prop.inventoryItemId).displayName;
			}

			prop.quantityInReportingUnit = UnitUtils
					.safeGetQuantityInReportingUnit(prop.physicalQuantity,
							prop.quantityInDefaultUnit, prop.reportingUnit);
		}
	}

	@Override
	public int compareTo(InventoryItemProp o) {
		if ((inventoryItemType == null) || (o.inventoryItemType == null))
			return 0;

		if (inventoryItemType.equals(o.inventoryItemType))
			return displayName.toLowerCase().compareTo(
					o.displayName.toLowerCase());

		return inventoryItemType.compareTo(o.inventoryItemType);
	}
}
